#!/usr/bin/bash
set -e

source ./mtail.properties

init(){
echo deploy init

# 判断目录是否存在
if [ ! -d /etc/mtail/  ];then
  sudo mkdir /etc/mtail/
  sudo chmod a+w /etc/mtail/
fi
sudo cat > /etc/mtail/node_keyword_count.mtail <<EOF
# 添加忽略文件过滤，该日志文件只解析 path/nms-monitor.log 日志文件
#	getfilename() !~ /nms-monitor.log/ {
#  stop
#  }
# the label value.
counter mtail_node_keyword_total by filename,alarmword
# Define some pattern constants for reuse in the patterns below key word
const PREFIX /^${KEYWORD}$/
/^/ +
/(?P<alarmword>([0-9a-zA-Z:*]+\s*)+)/ +
/$/ {
   PREFIX {
  		mtail_node_keyword_total[getfilename()][\$alarmword]++
	}
}
EOF

service
}

# 二进制直接启动
start(){
echo deploy start
tar -zxf ./mtail_3.0.0-rc47_Linux_x86_64.tar.gz
chmod 0755 mtail
sudo cp mtail /usr/local/bin
# mtail后台启动
nohup ./mtail -port 3903 --logs $LOGPATH --progs /etc/mtail --override_timezone=Local 2>&1 &

echo deploy end
}

# service化改造
service(){
echo deploy start
sudo tar -zxf ./mtail_3.0.0-rc47_Linux_x86_64.tar.gz
sudo chmod 0755 mtail
# 先停止,可重复部署
if [ -f /usr/lib/systemd/system/mtail.service ];then
sudo systemctl stop mtail
fi


sudo cp mtail /usr/sbin
sudo touch /usr/lib/systemd/system/mtail.service
sudo chmod o+w /usr/lib/systemd/system/mtail.service
sudo chmod a+x /usr/sbin/mtail
sudo cat << EOF > /usr/lib/systemd/system/mtail.service
[Service]
Type=simple
User=$USER
ExecStart=/usr/sbin/mtail -port 3903 --logs $LOGPATH --progs /etc/mtail -emit_prog_label=false
Restart=on-failure

[Install]
WantedBy=multi-user.target

[Unit]
Description=mtail service daemon
After=network.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable mtail
sudo systemctl start mtail
echo sudo systemctl status mtail
sudo systemctl status mtail
echo deploy end
}

init

